/**
 * main module
 *
 * @author strlst <e11907086@student.tuwien.ac.at>
 * @date 2020-11-05
 * @brief the context in which the compressor module is set up and subsequently used, additionally handles arguments and prints error information
 * @details none
 */

#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>

#include "compress.h"

#define INCORRECT_USAGE 1

/**
 * @brief kills program while printing terminating message
 * @details prints usage string before exiting using exit(...)
 */
void usage() {
    fprintf(stderr, "usage: osue-zip [-o outfile] [file...]\n\
  -o     writes to stdout if not specified\n\
  file   reads from stdin if no files are specified\n");
    exit(INCORRECT_USAGE);
}

/**
 * @brief parses arguments and initiates compressor
 * @details none
 * @param argc argument count
 * @param argv argument vector
 */
int main(int argc, char **argv) {
    char* opt_out = NULL;
    int c;

    /* argument parsing */
    while ((c = getopt(argc, argv, "o:")) != -1) {
        switch (c) {
            case 'o': opt_out = optarg;
                break;
            /* handle invalid option */
            case '?':
                usage();
                break;
            /* will never happen? */
            default:
                usage();
                break;
        }
    }

    /* query for presence of outfile */
    if (!opt_out)
        opt_out = "/dev/stdout";

    /* query for presence of infiles */
    if ((argc - optind) == 0) {
        compress("/dev/stdin", opt_out);
    } else {
        /* open for writing and close to clear outfile file before appending */
        /* appending only could lead to confusion if the file already existed */
        FILE *fd;
        if ((fd = fopen(opt_out, "w")) == NULL) {
            fprintf(stderr, "osue-zip: error opening specified file for writing: %s\n", strerror(errno));
            return EXIT_FAILURE;
        }
        if (fclose(fd) < 0) {
            fprintf(stderr, "osue-zip: error closing specified file: %s\n", strerror(errno));
            return EXIT_FAILURE;
        }

        /* loop over positional arguments */
        for (int i = optind; i < argc; i++) {
            if (compress(argv[i], opt_out) != EXIT_SUCCESS)
                return EXIT_FAILURE;
        }
    }

    return EXIT_SUCCESS;
}
